package com.tax.controller;

import com.alibaba.fastjson.JSONObject;
import com.tax.common.constant.CommonConstant;
import com.tax.common.util.StringsUtil;
import com.tax.config.exception.ApiException;
import com.tax.config.jwt.JwtUserInfo;
import com.tax.config.response.Response;
import com.tax.dto.req.LoginReq;
import com.tax.dto.req.TokenReq;
import com.tax.dto.res.LoginRes;
import com.tax.service.ITdUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@RestController
@Api(tags = "用户登录")
public class LoginController {

    @Resource(name = "stringRedisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private ITdUserService iTdUserService;

    @ApiOperation(value = "H5用户登录", notes = "用户登录",response = LoginRes.class)
    @RequestMapping(value = "/tax-h5/login",method=RequestMethod.POST)
    public Response<Object> h5Login(@Validated @RequestBody LoginReq req) throws ApiException {
        String tokenKey = "";
        //验证码登录
        if (req.getUserLoginType().equals(CommonConstant.USER_ACCESS_TOKEN_TYPE_VALIDCODE)) {
            tokenKey = StringsUtil.getUserValidcodeLoginKey(req.getTelephone());
        }
        //密码登录
        if (req.getUserLoginType().equals(CommonConstant.USER_ACCESS_TOKEN_TYPE_PASSWORD)) {
            tokenKey = StringsUtil.getUserPasswordLoginKey(req.getTelephone());
        }
        String token = redisTemplate.opsForValue().get(tokenKey);
        //获取用户信息
        TokenReq tokenReq = new TokenReq();
        tokenReq.setToken(token);
        Response<JwtUserInfo> res=iTdUserService.v2jwtUserInfo(tokenReq);

        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        data.put("userInfo", res.getData());
        return new Response(data);
    }

    @ApiOperation(value = "PC用户登录", notes = "用户登录",response = LoginRes.class)
    @RequestMapping(value = "/tax-pc/login",method=RequestMethod.POST)
    public Response<Object> pcLoing(@Validated @RequestBody LoginReq req){
        String tokenKey = "";
        //验证码登录
        if (req.getUserLoginType().equals("validcode")) {
            tokenKey = StringsUtil.getUserValidcodeLoginKey(req.getTelephone());
        }
        //密码登录
        if (req.getUserLoginType().equals("password")) {
            tokenKey = StringsUtil.getUserPasswordLoginKey(req.getTelephone());
        }
        String token = redisTemplate.opsForValue().get(tokenKey);
        Map<String,String> data = new HashMap<>();
        data.put("token",token);
        data.put("redirectUrl","");
        return new Response(data);
    }

}

